import React, { Component } from "react";
import {
  View,
  Text,
  Alert,
  ImageBackground,
  TouchableOpacity,
  StatusBar,
  ScrollView,
  DeviceEventEmitter,
  PermissionsAndroid,
  Platform,
  Linking,
} from "react-native";
import { Toast, WhiteSpace } from "@ant-design/react-native";
// import DeviceInfo from "react-native-device-info";
import { connect } from "react-redux";
import Icon from "components/Iconfont";
import { getStatusBarHeight } from "utils/adaptation";
import HomeTopSearch from "components/HomeTopSearch";
import { CZH, CZH_CN } from "language/complex-zh";
import { SZH, SZH_CN } from "language/simple-zh";
import {
  getStore,
  setStore,
  getMultiplPermissions,
  checekPermissions,
} from "utils";
import navBg from "assets/images/mainbg2.png";
import Tab from "components/Tab";
import CustomeQR from "components/CustomeQR";
import * as theme from "theme";

import styles from "./styles";
// import LbsModal from "./component/LbsModal";

// const { height: windowHeight } = Dimensions.get("window");
const nav = getStatusBarHeight();

class HomePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      unRead: null,
      url: "",
      waitTime: 2,
      selectedTab: 0,
      selectedInfoTab: 0,
    };
    const { navigation } = props;
    navigation.addListener("didFocus", this.screenDidFocus2);

    // keyRenderContentByHtml("<em>123</em>456789<em>1231</em>111111");

    //   const str = `您好，关于首次办理普通护照指南[link target="_blank"  url="https://www.gdzwfw.gov.cn/portal/guide/1144040055165867744440106042001"]
    //  请点击[/link]可了解更多详情。↵<br/>您可能还关注下列相关问题：↵[link submit="普通护照网上办理流程"]`;
    //   const filterData = keyRenderContentByTag(str);
    //   console.log(filterData);
  }

  componentDidMount() {
    const { dispatch } = this.props;

    this.screenDidFocus();
    this.listener = DeviceEventEmitter.addListener("NoticeLogin", () => {
      // 这里面是要调用的方法，比如：刷新
      // value:是下面页面在 通知 时 ，所传递过来的参数
      this.screenDidFocus();
    });
    this.listener2 = DeviceEventEmitter.addListener("NoticeUnLogin", () => {
      console.log("NoticeUnLogin"); // eslint-disable-line
      this.screenDidFocus();
    });
    this.listener3 = DeviceEventEmitter.addListener("NoticeHome", () => {
      console.log("NoticeHome"); // eslint-disable-line
      this.screenDidFocus();
    });
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }

    this.listener.remove();
    this.listener2.remove();
    this.listener3.remove();
  }

  onSelectPosition = val => {
    this.setState({ selectedTab: val });
  };

  onInfoSelectPosition = val => {
    this.setState({ selectedInfoTab: val });
  };

  screenDidFocus2 = () => {
    this.changeStatusBar();
  };

  screenDidFocus = () => {
    this.changeStatusBar();
  };

  // 修改状态栏
  changeStatusBar = () => {
    StatusBar.setBarStyle("light-content");
    StatusBar.setTranslucent(true);
    StatusBar.setBackgroundColor("#00000000");
  };

  back = () => {
    // const { navigation } = this.props;
    return (
      <TouchableOpacity
        onPress={() => {
          // navigation.navigate("Message");
          // 判断平台
          const { dispatch } = this.props;
          // 扫码服务

          if (Platform.OS === "android") {
            checekPermissions(PermissionsAndroid.PERMISSIONS.CAMERA).then(
              res => {
                // 未授权，调用授权待用户确认
                if (!res) {
                  // 获取读取存储卡权限，读取用户相册需要
                  getMultiplPermissions([
                    PermissionsAndroid.PERMISSIONS.CAMERA,
                    PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
                  ]).then(resInner => {
                    const CAMERA = resInner["android.permission.CAMERA"];
                    if (CAMERA === "granted") {
                      // navigation.navigate("QRScanner");
                      CustomeQR.openQR(global.lang_cn);
                    }
                  });
                } else {
                  checekPermissions(
                    PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
                  ).then(res2 => {
                    if (!res2) {
                      // 获取读取存储卡权限，读取用户相册需要
                      getMultiplPermissions([
                        PermissionsAndroid.PERMISSIONS.CAMERA,
                        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
                      ]).then(resInner => {
                        const CAMERA =
                          resInner["android.permission.RECORD_AUDIO"];
                        if (CAMERA === "granted") {
                          // navigation.navigate("QRScanner");
                          this.CustomeQR.openQR(global.lang_cn);
                        }
                      });
                    } else {
                      // navigation.navigate("QRScanner");
                      this.CustomeQR.openQR(global.lang_cn);
                    }
                  });
                }
              }
            );
          } else {
            // navigation.navigate("QRScanner");
            this.CustomeQR.openQR(global.lang_cn);
          }
        }}
      >
        <Icon
          name="scan"
          type="icon"
          color={theme.ColorBackgroundComp}
          size={20}
        />
      </TouchableOpacity>
    );
  };

  right = () => {
    const { navigation, publicData } = this.props;
    const { unRead = 0 } = this.state;
    return (
      <View style={styles.right}>
        <TouchableOpacity
          onPress={() => {
            // 消息提示

            if (publicData.isLogin) {
              navigation.navigate("MyNewsPage");
            } else {
              navigation.navigate("Login");
            }
          }}
          style={{ marginRight: 10 }}
        >
          {unRead > 0 && (
            <View style={styles.dot}>
              <Text
                style={{
                  fontSize: 10,
                  color: "#fff",
                  alignItems: "center",
                  alignSelf: "center",
                }}
              >
                {unRead}
              </Text>
            </View>
          )}

          <Icon
            name="news"
            type="icon"
            color={theme.ColorBackgroundComp}
            size={20}
          />
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            //

            // 读取用户选择的语音
            setStore("lang", global.lang_cn === "简体" ? "complex" : "simple");
            const { dispatch } = this.props;
            dispatch({
              type: "public/buryingPoint",
              payload: {
                behavior: global.lang_cn === "简体" ? "切换繁体" : "切换简体",
              },
            });
            getStore("lang").then(res => {
              if (res) {
                if (res === "simple") {
                  global.lang = SZH;
                  global.lang_cn = SZH_CN;
                } else {
                  global.lang = CZH;
                  global.lang_cn = CZH_CN;
                }
              }
              console.log("切换语言:", global.lang_cn); // eslint-disable-line
              // RNReload.reload();
              this.forceUpdate();
              DeviceEventEmitter.emit("NoticeUpdateLocale");
            });
          }}
        >
          {global.lang_cn === "简体" ? (
            <Icon
              name="simplifiedChinese"
              type="icon"
              color={theme.ColorBackgroundComp}
              size={20}
            />
          ) : (
            global.lang_cn === "繁体" && (
              <Icon
                name="traditionalChinese"
                type="icon"
                color={theme.ColorBackgroundComp}
                size={20}
              />
            )
          )}
        </TouchableOpacity>
      </View>
    );
  };

  test2 = keyWord => {
    // this.setState({ isShow: true });
    // MostSearch
    const { navigation } = this.props;
    navigation.navigate("MostSearch", { keyWord });
  };

  handleScroll = e => {
    const { contentOffset } = e.nativeEvent;
    const { y } = contentOffset;
    const percent = y > 0 ? y / 262 : 0;
    this.setState({ headerBg: `rgba(10,116,232,${percent})` });
    // console.log(e.nativeEvent);
  };

  render() {
    const { selectedTab, selectedInfoTab, headerBg } = this.state;
    const { navigation, dispatch } = this.props;
    return (
      <View style={styles.root}>
        <View style={[styles.header, { backgroundColor: headerBg }]}>
          <View style={styles.leftc}>{this.back()}</View>
          <View style={styles.rightc}>{this.right()}</View>
        </View>
        <ScrollView
          style={{ backgroundColor: theme.ColorBackgroundComp }}
          onScroll={this.handleScroll}
          scrollEventThrottle={16}
        >
          <ImageBackground
            source={navBg}
            resizeMode="cover"
            style={{
              height: 252 + nav,
            }}
          >
            <View style={styles.search}>
              <HomeTopSearch
                test={this.test2}
                dispatch={dispatch}
                navigation={navigation}
              />
            </View>
            <View style={styles.nav}>
              <Text style={styles.navTitle}>
                {global.lang.service.navTitle}
              </Text>
              <Text style={styles.navSubTitle}>
                {global.lang.service.navSubTitle}
              </Text>
            </View>
          </ImageBackground>
          <View style={styles.panel}>
            {/* 菜单 */}
            <Text style={styles.subTitle}>{global.lang.service.subTitle}</Text>
            <WhiteSpace />
            <WhiteSpace />
            <WhiteSpace />
            <WhiteSpace />
            <WhiteSpace />
          </View>
          <Tab
            customSty={{ paddingBottom: 15 }}
            values={[
              global.lang.service.personService,
              global.lang.service.rawService,
            ]}
            selectedIndex={selectedTab}
            onSelectChange={this.onSelectPosition}
          />
          {selectedTab === 0 ? (
            <View>
              <WhiteSpace />
              <Text>{global.lang.service.personService}</Text>
              <WhiteSpace />
            </View>
          ) : (
            <View>
              <WhiteSpace />
              <Text>{global.lang.service.rawService}</Text>
              <WhiteSpace />
            </View>
          )}
          <Tab
            customSty={{ width: 46, paddingBottom: 10, paddingTop: 10 }}
            values={[
              global.lang.infomation.infoSubTitle1,
              global.lang.infomation.infoSubTitle2,
              global.lang.infomation.infoSubTitle3,
            ]}
            selectedIndex={selectedInfoTab}
            onSelectChange={this.onInfoSelectPosition}
          />
          {selectedInfoTab === 0 ? (
            <View>
              <WhiteSpace />
              <Text>{global.lang.infomation.infoSubTitle1}</Text>
              <WhiteSpace />
            </View>
          ) : selectedInfoTab === 1 ? (
            <View>
              <WhiteSpace />
              <Text>{global.lang.infomation.infoSubTitle2}</Text>
              <WhiteSpace />
            </View>
          ) : (
            <View>
              <WhiteSpace />
              <Text>{global.lang.infomation.infoSubTitle3}</Text>
              <WhiteSpace />
            </View>
          )}
        </ScrollView>
        <CustomeQR
          ref={ref => {
            this.CustomeQR = ref;
          }}
          navigation={navigation}
        />
      </View>
    );
  }
}

export default connect((stores, mine) => ({
  publicData: stores.public,
  mine,
}))(HomePage);
